<%@ taglib uri="/tags/struts-bean" prefix="bean"%>
<%@ taglib uri="/tags/struts-html" prefix="html"%>
<%@ taglib uri="/tags/struts-logic" prefix="logic"%>
<%@ taglib uri="/tags/core" prefix="c"%>
<%@ taglib uri="/tags/fmt" prefix="fmt"%>
<script type="text/javascript">
//Tipo Unitario
function assignUType(){	
	var option = document.getElementById('amount').value;	
	var purchaseOrderList = document.getElementById('sizeList').value;	
	var listEmpty = false;
	//Si la lista tiene resultados se recorre
	//y verificar si estan checados
	if(purchaseOrderList >= 0){
		for(i= 0; i < purchaseOrderList; i++){						
			var checked = document.getElementById('purchaseOrdersVersionList[' + i + '].selectedPurchaseOrdersIds').checked;					
			if(checked){								
				listEmpty = true;
				break;				
			}					
		}	
	}		
	if(option == "" || parseInt( option ) == 0){
		alert('<bean:message key="warning.message.manualcharge.amont"/>');
	}else if(parseInt( purchaseOrderList ) < 0 ){
		alert('Seleccione un elemento del resultado de la busqueda');	
	}else if(!listEmpty){
		alert('Seleccione un elemento del resultado de la busqueda');	
	}else{
		document.getElementById('chargeType').value = 'U';
		document.getElementById('chargeTypeDescription').value = 'Unitario';
		var totalSum = 0;		
		for(i= 0; i < purchaseOrderList; i++){						
			var checked = document.getElementById('purchaseOrdersVersionList[' + i + '].selectedPurchaseOrdersIds').checked;			
			if(checked){								
				var unitPrice = document.getElementById('unitPrice['+ i +']').value = option;
				var capacity = document.getElementById('capacityId['+ i +']').value;
				var r1 = parseFloat(capacity.replace(/,/g, ""));
				var r2 = parseFloat(unitPrice.replace(/,/g, ""));
				var result = r1*r2;
				totalSum += result;
				document.getElementById('itemQuantity['+ i +']').value = addCommas( decimales( result, 4 ) );
			}					
		}
		document.getElementById('total').value = addCommas( decimales( totalSum, 4 ) );		
	}		
}
//Tipo Ponderado
function assignPType(){
	var option = document.getElementById('amount').value;	
	var purchaseOrderList = document.getElementById('sizeList').value;	
	var listEmpty = false;
	//Si la lista tiene resultados se recorre
	//y verificar si estan checados	
	if(purchaseOrderList >= 0){
		for(i= 0; i < purchaseOrderList; i++){						
			var checked = document.getElementById('purchaseOrdersVersionList[' + i + '].selectedPurchaseOrdersIds').checked;					
			if(checked){											
				listEmpty = true;
				break;					
			}					
		}	
	}		
	//Recorro la lista para obtener la suma de capacidades
	var sumCapacity = 0;
	if(purchaseOrderList >= 0){
		for(i= 0; i < purchaseOrderList; i++){						
			var checked = document.getElementById('purchaseOrdersVersionList[' + i + '].selectedPurchaseOrdersIds').checked;					
			if(checked){	
				var capacity = document.getElementById('capacityId['+ i +']').value;
				var capacityValue = parseFloat(capacity.replace(/,/g, ""));										
				sumCapacity += capacityValue;
			}					
		}	
	}
	if(option == "" || parseInt( option ) == 0){
		alert('<bean:message key="warning.message.manualcharge.amont"/>');
	}else if(parseInt( purchaseOrderList ) < 0 ){
		alert('Seleccione un elemento del resultado de la busqueda');	
	}else if(!listEmpty){
		alert('Seleccione un elemento del resultado de la busqueda');	
	}else{
		document.getElementById('chargeType').value = 'P';
		document.getElementById('chargeTypeDescription').value = 'Ponderado';		
		var res = 0;
		var totalSum = 0;
		if(purchaseOrderList >= 0){
			for(i= 0; i < purchaseOrderList; i++){						
				var checked = document.getElementById('purchaseOrdersVersionList[' + i + '].selectedPurchaseOrdersIds').checked;					
				if(checked){	
					var capacity = document.getElementById('capacityId['+ i +']').value;
					var capacityValue = parseFloat(capacity.replace(/,/g, ""));	
					
					res = option *(capacityValue / sumCapacity);
					totalSum += res;
					document.getElementById('unitPrice['+ i +']').value = addCommas( decimales( res/capacityValue, 4 ) );
					var quantityTotal = res * capacityValue;
					document.getElementById('itemQuantity['+ i +']').value = addCommas( decimales( res, 4 ) );
				}					
			}	
		}
		document.getElementById('total').value = addCommas( decimales( totalSum, 4 ) );	
	}		
	
}

function validate(){
    var errors = "";
    var description = document.getElementById('description').value;
    var costElement = document.getElementById('costElementId').value;    
    var amount = document.getElementById('amount').value;
                                         	         
	if(description == "") {
    	errors += ' <bean:message key="lable.plants.validation.description"/>\n';
    } 
    if(costElement == -1){                
    	errors = ' <bean:message key="warning.message.manualcharge.costelement"/>\n';			  
    }
    if(amount == "" || parseInt( amount ) == 0) {
    	errors += ' <bean:message key="warning.message.manualcharge.amont"/>\n';
    } 
    if( errors == "" ){
        return true;
    }else{
        alert( '<bean:message key="label.common.errors"/> : \n' + errors );
		return false;
    }
}
//funcion que verifica cuando es tipo Manual
function changeToManual(forma, index){	
	document.getElementById('chargeType').value = 'M';
	document.getElementById('chargeTypeDescription').value = 'Manual';
	var purchaseOrderList = document.getElementById('sizeList').value;		
	var sumCapacity = 0;
	if(purchaseOrderList >= 0){
		for(i= 0; i < purchaseOrderList; i++){						
			var checked = document.getElementById('purchaseOrdersVersionList[' + i + '].selectedPurchaseOrdersIds').checked;					
			if(checked){	
				var itemQuantity = document.getElementById('itemQuantity['+ i +']').value;
				var itemQuantityNumeric = parseFloat(itemQuantity.replace(/,/g, ""));										
				sumCapacity += itemQuantityNumeric;
				document.getElementById('itemQuantity['+ i +']').value = addCommas( decimales( itemQuantityNumeric, 4 ) );
			}					
		}	
		document.getElementById('total').value = addCommas( decimales( sumCapacity, 4 ) );	
	}
}
//Funcion que verifica los checkbox
function funcChecBox(forma, index){			
	var purchaseOrderList = document.getElementById('sizeList').value;
	var isChecked = document.getElementById('purchaseOrdersVersionList[' + index + '].selectedPurchaseOrdersIds').checked;
	var cT = document.getElementById('chargeTypeDescription').value;
	if(cT != ""){
		if(!isChecked){
			document.getElementById('itemQuantity['+ index +']').disabled = true;
			document.getElementById('chargeType').value = 'M';
			document.getElementById('chargeTypeDescription').value = 'Manual';
			document.getElementById('itemQuantity['+ index +']').value = "";
			document.getElementById('unitPrice['+ index +']').value = "";
			var sumCapacity = 0;
			if(purchaseOrderList >= 0){
				for(i= 0; i < purchaseOrderList; i++){						
					var checked = document.getElementById('purchaseOrdersVersionList[' + i + '].selectedPurchaseOrdersIds').checked;					
					if(checked){	
						var itemQuantity = document.getElementById('itemQuantity['+ i +']').value;
						var itemQuantityNumeric = parseFloat(itemQuantity.replace(/,/g, ""));										
						sumCapacity += itemQuantityNumeric;
					}					
				}	
				document.getElementById('total').value = addCommas( decimales( sumCapacity, 4 ) );	
			}	
		}else{
			document.getElementById('itemQuantity['+ index +']').disabled = false;	
		}
	}
}
</script>
<html:form action="/filterSearchPurchaseOrders"  method="POST">
<html:hidden styleId="sizeList" name="ManualChargesForm" property="sizeList"/>
<table width="60%" align="center" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
	<tr>
		<td class="titulocolumna" align="center" colspan="5"><bean:message key="label.manual.charges.table.title" /></td>
	</tr>
	<tr>
		<td class="etiqueta"><bean:message key="label.transports.query.transport"/> </td>
		<td class="etiqueta_campo" style="text-align: left;">
			<html:select name="ManualChargesForm" property="filterSearch.transportIdFilter" style="width:160px" styleClass="campo_texto">
                <html:option value="-1"><bean:message key="label.program.purchase.selectanoption"/></html:option>
                <html:optionsCollection name="transportListViews" value="transportIdentifier" label="transportDescription"/>
            </html:select>   
		</td>
		<td class="etiqueta"><bean:message key="label.manual.charges.transit"/> </td>		
		<td class="etiqueta_campo" style="text-align: left;">
			 <html:select name="ManualChargesForm" property="filterSearch.transitTypeFilter" style="width:160px" styleClass="campo_texto">
	            <html:option value="-2"><bean:message key="label.program.purchase.selectanoption"/></html:option>
                <html:option value="-1">Todos</html:option>
                <html:option value="1">Transito</html:option>
                <html:option value="0"><bean:message key="label.versions.purchaseOrders.menu" /> </html:option>
            </html:select> 
		</td>		
		<td class="etiqueta_campo" align="center" rowspan="2"><input type="submit"  value="<bean:message key="label.common.query"/>" class="boton"/></td>				
	</tr>
	<tr>
		<td class="etiqueta"><bean:message key="label.versions.startDate"/> </td>
		<td class="etiqueta_campo" style="text-align: left;">
			<html:select styleId="initPeriodSelect" name="ManualChargesForm" property="filterSearch.initPeriodFilter" style="width:160px" styleClass="campo_texto">
				<html:optionsCollection name="biWeekList" value="biweekPeriodId" label="description"/>
			</html:select>
		</td>		
		<td class="etiqueta"><bean:message key="label.versions.endDate"/> </td>
		<td class="etiqueta_campo" style="text-align: left;">
			<html:select styleId="endPeriodSelect" name="ManualChargesForm" property="filterSearch.endPeriodFilter" style="width:160px" styleClass="campo_texto" >
				<html:optionsCollection name="biWeekList" value="biweekPeriodId" label="description"/>
			</html:select>
		</td>		
	</tr>		
</table>
</html:form>
<br />
<html:form action="/saveManualCharge" onsubmit="return validate();" method="POST">
<input type="hidden" value="<bean:write name="ManualChargesForm" property="view.chargeType"/>"></input> 
<table width="60%" align="center" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
	<html:hidden name="ManualChargesForm" property="view.chargeType" styleId="chargeType"/>
	<tr>
		<td class="titulocolumna" align="center" colspan="6"><bean:message key="label.manual.charges.table.title" /></td>
	</tr>
	
	<tr>
		<td class="etiqueta"><bean:message key="message.futurepurchase.customer.description"/> </td>
		<td class="etiqueta_campo" style="text-align: left;" colspan="2"> <html:text name="ManualChargesForm" styleId="description" property="view.description" style="width:200px" styleClass="campo_texto" onfocus="this.select();" /> </td>		
		<td class="etiqueta"><bean:message key="label.customerfuturepurchase.type.shortName"/> </td>
		<td class="etiqueta_campo" style="text-align: left;"> <input id="chargeTypeDescription" class="campo_texto" style="20px;" disabled="disabled" type="text"> </td>
	</tr>
	
	<tr>
		<td class="etiqueta"><bean:message key="label.manual.charges.elementcost"/> </td>
		<td class="etiqueta_campo" style="text-align: left;">
			<html:select name="ManualChargesForm" styleId="costElementId" property="view.costElementId" style="width:160px" styleClass="campo_texto" >
				<html:option value="-1"><bean:message key="label.program.purchase.selectanoption"/></html:option>
				<html:optionsCollection name="costElementsList" value="costElementID" label="costElementCode"/>
			</html:select>
		</td>
		<td class="etiqueta"><bean:message key="label.creditline.balance.amount"/> </td>
		<td class="etiqueta_campo" style="text-align: left;"><html:text name="ManualChargesForm" styleId="amount" property="view.amount" styleClass="columnanumero" onfocus="this.select();" onkeydown="return (numeric(event, 1) && noPaste(event, this));" onkeyup="extractNumber(this,4,false);" /></td>
		<td class="etiqueta_campo" style="text-align: left;"><input type="button" onclick="assignPType();" value="<bean:message key="label.manual.charges.price.balance"/>" class="boton"> <input type="button" value="<bean:message key="label.manual.charges.price.unitprice"/>" onclick="assignUType();" class="boton"> </td>				
	</tr>
</table>
<br />
<table id="purchaseOrdersId" width="48%" align="center" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
	<tr>
		<td class="titulocolumna" align="center"> &nbsp; </td>
		<td class="titulocolumna" align="center"><bean:message key="label.futurepurchase.query.period" /></td>
		<td class="titulocolumna" align="center"><bean:message key="error.code" /></td>
		<td class="titulocolumna" align="center"><bean:message key="label.transports.query.capacity" /></td>
		<td class="titulocolumna" align="center"><bean:message key="label.manual.charges.price.unitprice" /></td>
		<td class="titulocolumna" align="center"><bean:message key="label.creditline.balance.amount" /></td>
	</tr>
	<logic:notEmpty name="ManualChargesForm" property="purchaseOrdersVersionList">
		<logic:iterate id="row" name="ManualChargesForm" property="purchaseOrdersVersionList" indexId="int_i">
			<tr class="<%=((int_i.intValue()%2)==0?"columnadatoPar":"columnadatoNon")%>">
				<td align="center">					
					<input type="checkbox" onclick="funcChecBox(this.form, '<c:out value="${int_i}"/>')" name="selectedPurchaseOrdersIds" id='purchaseOrdersVersionList[<c:out value="${int_i}"/>].selectedPurchaseOrdersIds' value='<c:out value="${row.purchaseOrderVersionId}"/>'>					
				</td>
				<td align="center"><bean:write name="row" property="periodDescription"/></td>
				<td align="center"><bean:write name="row" property="code"/></td>
				<td align="center">
					<bean:write name="row" property="capacityStringValue"/>
					<input id="capacityId[<c:out value="${int_i}"/>]" type="hidden" value="<bean:write name="row" property="capacityStringValue"/>">
				</td>
				<td align="center"><input id="unitPrice[<c:out value="${int_i}"/>]" type="text" class="columnanumero" readonly="readonly"></td>
				<td align="center"><input id="itemQuantity[<c:out value="${int_i}"/>]" type="text" style="text-align: right;" name='purchaseOrdersVersionList[<c:out value="${int_i}"/>].amount' class="columnanumero" onkeyup="extractNumber(this,4,false);" onfocus="this.select();" onkeydown="return (numeric(event, 1) && noPaste(event, this));" onblur="changeToManual(this.form, '<c:out value="${int_i}"/>')" > </td>
			</tr>			
		</logic:iterate>
			<tr>
				<td class="titulocolumna" align="right" colspan="4">Total &nbsp;</td>
				<td class="titulocolumna" >&nbsp;</td>
				<td class="titulocolumna" ><input id="total" type="text" class="columnanumero" readonly="readonly"> </td>
			</tr>
			<tr>				
				<td class="titulocolumna" colspan="6" align="right" >
					<input type="submit" value="Grabar" class="boton">
				</td>
			</tr>
	</logic:notEmpty>			
</table>
</html:form>
<br />
<br />
<table width="60%" align="center" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
	<tr>		
		<td align="center" class="titulo_lista_interna">			
			<html:button property="back" onclick="location.href ='showManualChargesList.do'" styleClass="boton"><bean:message key="label.common.back"/></html:button>
		</td>
	</tr>
</table>
<br />
<br />
<script>
var endP = document.getElementById("endPeriodSelect");
endP.selectedIndex = endP.options.length-1;
</script>